﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Text;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json;
using System.Net.Http;

namespace VM.Common.http
{


    public class HttpClientRequest
    {
        /// <summary>
        /// Seivice URL
        /// </summary>
        public string Url { get; set; }
        /// <summary>
        /// 内容
        /// </summary>
        public string Content { get; set; }
        /// <summary>
        /// Cookie，保证登录后，所有访问持有一个Cookie；
        /// </summary>
        static CookieContainer Cookie = new CookieContainer();
        private readonly HttpClient _httpClient;
        /// <summary>
        /// HTTP访问
        /// </summary>
        public string AsyncRequest()
        {
            HttpWebRequest httpRequest = WebRequest.Create(Url) as HttpWebRequest;

            httpRequest.Method = "POST";
            httpRequest.ContentType = "application/json";
            httpRequest.CookieContainer = Cookie;
            httpRequest.Timeout = 1000 * 60 * 10;//10min

            using (Stream reqStream = httpRequest.GetRequestStream())
            {
                JObject jObj = new JObject();
                jObj.Add("format", 1);
                jObj.Add("useragent", "ApiClient");
                jObj.Add("rid", Guid.NewGuid().ToString().GetHashCode().ToString());
                jObj.Add("parameters", Content);
                jObj.Add("timestamp", DateTime.Now);
                jObj.Add("v", "1.0");
                string sContent = jObj.ToString();
                var bytes = Encoding.UTF8.GetBytes(sContent);
                reqStream.Write(bytes, 0, bytes.Length);
                reqStream.Flush();
            }
            using (var repStream = httpRequest.GetResponse().GetResponseStream())
            {
                using (var reader = new StreamReader(repStream))
                {
                    return ValidateResult(reader.ReadToEnd());
                }
            }
        }

        private static string ValidateResult(string responseText)
        {
            if (responseText.StartsWith("response_error:"))
            {
                return responseText.TrimStart("response_error:".ToCharArray());
            }
            return responseText;
        }


        public string AsyncRequestSendMsg(int OrgId, string PhoneNo)
        {
            string url = "http://123.60.154.183:5658/ms/mss/publicPhoneCode";
            HttpWebRequest httpRequest = WebRequest.Create(url) as HttpWebRequest;

            httpRequest.Method = "POST";
            httpRequest.ContentType = "application/json";
            httpRequest.CookieContainer = new CookieContainer();
            httpRequest.Timeout = 1000 * 60 * 10; // 10 minutes


            JObject jObj = new JObject();
            jObj.Add("orgid", OrgId);
            jObj.Add("phone", PhoneNo);

            string requestBody = jObj.ToString();

            byte[] requestBodyBytes = Encoding.UTF8.GetBytes(requestBody);
            httpRequest.ContentLength = requestBodyBytes.Length;

            using (Stream reqStream = httpRequest.GetRequestStream())
            {
                reqStream.Write(requestBodyBytes, 0, requestBodyBytes.Length);
            }
            try
            {
                using (var response = httpRequest.GetResponse() as HttpWebResponse)
                {
                    if (response.StatusCode == HttpStatusCode.OK)
                    {
                        using (var reader = new StreamReader(response.GetResponseStream()))
                        {
                            return ValidateResult(reader.ReadToEnd());
                        }
                    }
                    else
                    {
                        // Handle other status codes here
                        return "错误: " + response.StatusCode.ToString();
                    }
                }
            }
            catch (Exception e)
            {
                string s = e.Message.ToString();
                return s;
            }


        }

        public async Task<string> PostData(string jsonData)
        {
            try
            {
                // 构造请求URL
                var apiUrl = "http://150.158.53.230:5658/ms/mss/publicPhoneCode";
                var requestUrl = new Uri(apiUrl);

                // 构造请求内容
                var content = new StringContent(jsonData, Encoding.UTF8, "application/json");

                // 发送POST请求并获取响应
                var response = await _httpClient.PostAsync(requestUrl, content);

                // 确保响应成功
                response.EnsureSuccessStatusCode();

                // 读取响应内容
                var responseContent = await response.Content.ReadAsStringAsync();

                // 返回响应内容
                return responseContent;
            }
            catch (HttpRequestException ex)
            {
                // 处理请求异常
                Console.WriteLine($"发送POST请求时发生异常：{ex.Message}");
                throw;
            }
        }
    }


}